package gw.com.android.terminal;

import android.os.Bundle;

import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.chart.output.utils.ChartConfig;
import com.gwtsz.chart.output.utils.GTTFormularContent;
import com.gwtsz.chart.output.utils.GTTIndexDataRequest;
import com.gwtsz.chart.output.utils.GTTKDataManager;
import com.gwtsz.chart.output.utils.GTTKDataModel;
import com.gwtsz.chart.output.utils.GTTNotifyModel;
import com.gwtsz.chart.output.utils.GTTTimeDataModel;
import com.gwtsz.gts2.hx.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.model.DataManager;
import gw.com.android.ui.BaseActivity;
import gw.com.android.ui.WebPageActivity;
import gw.com.android.ui.account.LoginActivity;
import gw.com.android.ui.account.ModifyPassActivity;
import gw.com.android.ui.chart.ReqDataUtils;
import gw.com.android.ui.dialog.BaseDialog;
import gw.com.android.ui.dialog.PopupConfirmDialog;
import gw.com.android.utils.PackStatis;
import gw.com.android.utils.ServerConnnectUtil;
import gw.com.jni.library.terminal.DataListener;
import gw.com.jni.library.terminal.GTSConst;
import www.com.library.app.AppActivities;
import www.com.library.app.Logger;
import www.com.library.dialog.BasePopWindow;
import www.com.library.model.DataItemDetail;
import www.com.library.util.JsonUtil;
import www.com.library.util.NetworkMonitor;
import www.com.library.util.NetworkReceiver;
import www.com.library.view.LoadingDialog;

/**
 * 跟jni交互的通知关联类
 * Created by reeta.zou on 2016/7/1.
 */
public class GTSDataListener extends DataListener {

    private NetworkReceiver mReceiver;
    public String mContent = "";
    public static int curSeq = 100;
    /**
     * 主界面当前开启次数
     */
    public static int mainNum = 0;

    /**
     * 图标界面开启次数
     */
    public static int chartNum = 0;

    /**
     * 添加自选开启次数
     */
    public static int quoteAddNum = 0;

    //下单相关的seq的集合数据
    public HashMap<String, String> seqList = new HashMap<>();

    public GTSDataListener() {
        mReceiver = new NetworkReceiver();
        /* Registers BroadcastReceiver to track network connection changes. */
    }

    private static GTSDataListener instance = null;

    public static GTSDataListener instance() {
        if (instance == null) {
            instance = new GTSDataListener();
        }
        return instance;
    }

    /**
     * 注册网络监听事件
     */
    public void subscribe() {
        /* Listener to network state change */
        mReceiver.register(AppMain.getApp(), new NetworkReceiver.NetWorkListener() {
            @Override
            public void onNetWorkState(boolean hasNetWork) {
                RxBus.getInstance().post(GTSConst.REPLY_NETWORK_STATE + "", hasNetWork);
                BaseActivity mOwnerAct = (BaseActivity) AppActivities.getSingleton().currentActivity();
                if (mOwnerAct == null) {
                    return;
                }

                if (!hasNetWork) {
                    ServerConnnectUtil.instance().cancelTask(true);
                    ServerConnnectUtil.instance().isNetConnect = false;
                    AppTerminal.instance().setNetWorkState(AppContances.NET_WORK_NO_TYPE, false);
                    ServerConnnectUtil.instance().connnectTimeOutToast(
                            ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1008));
                    Logger.e("断开网络连接。。。");
                } else {
                    //如果用户已经登录，则网络连上后通知接口
                    Logger.e("建立网络连接。。。");
                    ServerConnnectUtil.instance().isNetConnect = true;
                    AppTerminal.instance().setNetWorkState(NetworkMonitor.getNetworkType(mOwnerAct), true);
                    if (!(mOwnerAct instanceof LoginActivity) && GTConfig.instance().hasShowMain) {
                        ServerConnnectUtil.instance().initTimerTask();
                    }
                }
            }
        });
    }


    /**
     * 注销网络监听事件
     */
    public void unsubscribe() {
        /* Unsubscribe to network state change */
        mReceiver.unregister(AppMain.getApp());
    }

    /**
     * 添加下单的seq
     *
     * @param key
     * @param value
     */
    public void addSeqList(String key, String value) {
        Logger.e("addSeqList key " + key + ", " + value);
        seqList.put(key, value);
    }

    /**
     * 删除下单的seq
     *
     * @param key
     */
    public void removeSeqList(String key) {
        if (seqList.containsKey(key)) {
            seqList.remove(key);
        }
    }

    /**
     * K线图、分时图数据返回的回调结果处理
     *
     * @param cmd
     * @param iNotification 产品号
     * @param object
     * @param iValue        错误码 0 代表成功， 非0代表出错
     */
    public void onServerResponse(int cmd, int iNotification, Object object, final int iValue, final int uSeq) {
        Bundle bundle = new Bundle();
        switch (cmd) {
            //K线图返回的回调结果处理
            case GTSConst.REPLY_KLINEDATA_LIST: {
                if (object instanceof GTTNotifyModel) {
                    final GTTNotifyModel obj = (GTTNotifyModel) object;
                    GTTFormularContent mSuperFormularContent = new GTTFormularContent();
                    GTTFormularContent mSecondFormularContent = new GTTFormularContent();
                    Logger.i("onServerResponse K线图数据回包 cmd = " + cmd + " uCodeId = " + obj.uiCodeID + " uInterval = " + obj.uiInterval + " uParam = " + obj.uiParam + " uCurTime = " + obj.uiStartTime + " nShNum = " + obj.nShNum + ",iValue = " + iValue + ", uSeq = " + uSeq);
                    final ArrayList<GTTKDataModel> mKLineList = new ArrayList<>();
                    AppTerminal.instance().getKLineDataList(obj.uiCodeID, obj.uiInterval, obj.uiParam, obj.uiStartTime, obj.nShNum, mKLineList);
                    boolean isRefresh = false;
                    if (obj.nShNum != 0) {
                        //异常情况下，只有第一次刷新请求的时候需要添加历史数据刷新ui
                        if (iValue != 0) {
                            if (obj.uiAppend == 0) {
                                isRefresh = true;
                            }
                        } else {
                            isRefresh = true;
                        }
                        if (isRefresh) {
                            Logger.i("onServerResponse mKLineList.size = " + mKLineList.size());
                            if (mKLineList.size() > 0) {
                                final GTTIndexDataRequest gttIndexDataRequest = ReqDataUtils.instance().reqIndictorData(obj.uiCodeID, -mKLineList.size(), obj.uiStartTime, 1);
                                //获取指标参数
                                AppTerminal.instance().getFormularContent(ChartConfig.instance().getMainKType(), mSuperFormularContent, 0);
                                mSuperFormularContent.setParamNum();
                                AppTerminal.instance().getFormularContent(ChartConfig.instance().getSecondKType(), mSecondFormularContent, 0);
                                bundle.putSerializable("mGttIndexDataRequest", gttIndexDataRequest);
                            }
                        }
                    }

                    bundle.putSerializable("GTTNotifyModel", obj);
                    bundle.putSerializable("SuperFormular", mSuperFormularContent);
                    bundle.putSerializable("SecondFormular", mSecondFormularContent);
                    bundle.putSerializable("mKLineList", mKLineList);
                } else {
                    Logger.i("onServerResponse K线图数据回包 cmd = " + cmd + " iNotification = " + iNotification + ",iValue = " + iValue);
                }
                bundle.putInt("iNotification", iNotification);
                bundle.putInt("iValue", iValue);
                RxBus.getInstance().post(GTSConst.REPLY_KLINEDATA_LIST + "", bundle);
            }
            break;
            //分时图返回的回调结果处理
            case GTSConst.REPLY_UPTRENDDATA_LIST: {
                if (object instanceof GTTNotifyModel) {
                    final GTTNotifyModel obj = (GTTNotifyModel) object;
                    final ArrayList<GTTTimeDataModel> mTimeList = new ArrayList<>();
                    AppTerminal.instance().getUptrendDataList(obj.uiCodeID, obj.uiStartTime, mTimeList);
                    Logger.i("onServerResponse 分时图数据回包 modelArrayList.size = " + mTimeList.size());

                    bundle.putSerializable("GTTNotifyModel", obj);
                    bundle.putSerializable("mTimeList", mTimeList);
                } else {
                    Logger.i("onServerResponse 分时图数据回包 cmd = " + cmd + " iNotification = " + iNotification + ",iValue = " + iValue);
                }
                bundle.putInt("iNotification", iNotification);
                bundle.putInt("iValue", iValue);
                RxBus.getInstance().post(GTSConst.REPLY_UPTRENDDATA_LIST + "", bundle);
            }
            break;
        }
    }

    /**
     * http请求返回的回调结果处理
     *
     * @param cmd
     * @param iNotification
     * @param strObject
     * @param iValue
     */
    public void onServerResponse(int cmd, final int iNotification, int iValue, String strObject) {
        switch (cmd) {
            case GTSConst.REPLY_LOGIN_RESULT:
                Logger.i("onServerResponse 登录回包接收到回调 iNotification = " + iNotification + " iValue = " + iValue);
                //被强制登出
                if (iNotification == AppContances.LOGIN_FORCE) {
                    ServerConnnectUtil.instance().setQuoteState(false);
                    ServerConnnectUtil.instance().setTradeState(false);
                    final BaseActivity mOwnerAct = (BaseActivity) AppActivities.getSingleton().currentActivity();
                    //被踢原因 1用户被禁用 2账号被禁用 3修改密码被登出 其他被踢出
                    if (iValue == 1004) {
                        if (mOwnerAct instanceof ModifyPassActivity) {// APP在修改密码这个界面除外,不接收修改密码踢出通知
                            return;
                        }
                        //忘记密码界面，不接收修改密码踢出通知
                        if (mOwnerAct instanceof WebPageActivity) {
                            if (WebPageActivity.showTitle.equals(AppMain.getAppString(R.string.login_menu_forgot_password))) {
                                return;
                            }
                        }
                    }
                    mContent = ConfigUtil.instance().getErrorConfigObject().optString(iValue + "");
                    GTConfig.instance().mHasKickOut = true;
                    ServerConnnectUtil.instance().setQuoteState(false);
                    ServerConnnectUtil.instance().setTradeState(false);
                    if (mOwnerAct == null || mOwnerAct.isFinishing() || mOwnerAct instanceof LoginActivity) {
                        //登录界面被登出提示超时提示
                        if (null != mOwnerAct && mOwnerAct instanceof LoginActivity) {
                            GTConfig.instance().mHasKickOut = false;
                            RxBus.getInstance().post(GTSConst.REPLY_LOGIN_RESULT + "", bundleRxBus(iNotification, 1100, strObject));
                        }
                        return;
                    }
                    mOwnerAct.runOnUiThread(new Runnable() {
                        public void run() {

                            if (null != LoadingDialog.instance() && LoadingDialog.instance().getOwnerActivity() != null && !LoadingDialog.instance().getOwnerActivity().isFinishing()) {
                                LoadingDialog.instance().dismiss();
                            }
                            if (null != BaseDialog.instance() && BaseDialog.instance().getOwnerActivity() != null && !BaseDialog.instance().getOwnerActivity().isFinishing()) {
                                BaseDialog.instance().dismiss();
                            }
                            if (null != BasePopWindow.instance() && BasePopWindow.instance().activity != null && !BasePopWindow.instance().activity.isFinishing()) {
                                BasePopWindow.instance().hidden();
                            }
                            PopupConfirmDialog.getKickOut(mOwnerAct, mContent);
                            RxBus.getInstance().post(GTSConst.REPLY_STATUS_FORCELOGIN, true);
                        }
                    });
                } else {
                    if (iValue == 1) {
                        final BaseActivity mOwnerAct = (BaseActivity) AppActivities.getSingleton().currentActivity();
                        if (null != mOwnerAct && !(mOwnerAct instanceof LoginActivity)) {
                            GTConfig.instance().mHasKickOut = true;
                            ServerConnnectUtil.instance().setQuoteState(false);
                            ServerConnnectUtil.instance().setTradeState(false);
                            mContent = ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1004);
                            mOwnerAct.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    PopupConfirmDialog.getKickOut(mOwnerAct, mContent);
                                }
                            });
                        }

                    } else if (iValue == 34) {
                        final BaseActivity mOwnerAct = (BaseActivity) AppActivities.getSingleton().currentActivity();
                        if (null != mOwnerAct && !(mOwnerAct instanceof LoginActivity)) {
                            GTConfig.instance().mHasKickOut = true;
                            ServerConnnectUtil.instance().setQuoteState(false);
                            ServerConnnectUtil.instance().setTradeState(false);
                            mContent = ConfigUtil.instance().getErrorConfigObject().optString(iValue + "");
                            mOwnerAct.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    PopupConfirmDialog.getKickOut(mOwnerAct, mContent);
                                }
                            });
                        }
                    }
                    RxBus.getInstance().post(GTSConst.REPLY_LOGIN_RESULT + "", bundleRxBus(iNotification, iValue, strObject));
                }
                break;
            case GTSConst.REPLY_NETWORK_STATE:
                if (iValue == 0) {
                    ServerConnnectUtil.instance().showProgress(iNotification);
                }
                break;
            case GTSConst.REPLY_QLOGIN_STATE:
                Logger.e("onServerResponse 重连行情服务器状态 iNotification = " + iNotification + " iValue = " + iValue);
                if (iNotification == AppContances.LOGIN_OK) {
                    DataManager.instance().clearCodes();
                    RxBus.getInstance().post(GTSConst.REPLY_QLOGIN_STATE + "", true);
                    ServerConnnectUtil.instance().setQuoteState(true);
                } else {
                    RxBus.getInstance().post(GTSConst.REPLY_QLOGIN_STATE + "", false);
                    ServerConnnectUtil.instance().setQuoteState(false);
                }
                break;
            case GTSConst.REPLY_TLOGIN_STATE:
                Logger.e("onServerResponse 重连交易服务器状态 iNotification = " + iNotification + " iValue = " + iValue);
                if (iNotification == AppContances.LOGIN_OK) {
//                    DataManager.instance().clearCodes();
                    RxBus.getInstance().post(GTSConst.REPLY_TLOGIN_STATE + "", true);
                    ServerConnnectUtil.instance().setTradeState(true);
                } else {
                    RxBus.getInstance().post(GTSConst.REPLY_TLOGIN_STATE + "", false);
                    ServerConnnectUtil.instance().setTradeState(false);
                }
                if (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_GUEST) {
                    return;
                }
                break;
            case GTSConst.REPLY_DICT_LIST:
                Logger.e("onServerResponse 重连数据字典回包 iNotification = " + iNotification + " iValue = " + iValue);
                RxBus.getInstance().postSticky(GTSConst.REPLY_DICT_LIST + "", bundleRxBus(iNotification, iValue, strObject));
                break;
            case GTSConst.REPLY_ACCOUNT_ADD:
            case GTSConst.REPLY_ACCOUNT_UPDATE: {
                cmd = GTSConst.REPLY_ACCOUNT_UPDATE;
//                Logger.i("onServerResponse 资金栏信息接收到回调 iNotification = " + iNotification + " iValue = " + iValue);
                if (JsonUtil.isJsonData(strObject)) {
                    DataManager.instance().setAccount(strObject);
                }
                RxBus.getInstance().postSticky(GTSConst.REPLY_ACCOUNT_UPDATE + "", DataManager.instance().mAccount);
                break;
            }
            case GTSConst.REPLY_MARGIN_UPDATE: {
                Logger.i("onServerResponse 层级保证金接收到回调REPLY_MARGIN_UPDATE iNotification = " + iNotification + " iValue = " + iValue);
                DataManager.instance().updateMarginOff(iNotification);
                RxBus.getInstance().post(GTSConst.REPLY_MARGIN_UPDATE + "", bundleRxBus(iNotification, iValue, strObject));
                break;
            }
            case GTSConst.REPLY_SYMBOL_ALLLIST: {
                Logger.i("onServerResponse 行情所有板块产品回包接收到回调REPLY_SYMBOL_ALLLIST iNotification = " + iNotification + " iValue = " + iValue + "  strObject =");
                if (JsonUtil.isJsonData(strObject)) {
                    DataManager.instance().addAllTickList(strObject);
                }
                if (!DataManager.instance().getLoadDataState(iNotification + "")) {
                    DataManager.instance().setLoadDataState(iNotification + "", true);
                }

                RxBus.getInstance().postSticky(GTSConst.REPLY_SYMBOL_ALLLIST + "", bundleRxBus(iNotification, iValue, strObject));
            }
            break;
            case GTSConst.REPLY_SYMBOL_LIST: {
                Logger.i("onServerResponse 行情列表回包接收到回调REPLY_SYMBOL_LIST iNotification = " + iNotification + " iValue = " + iValue);
                if (null != strObject && JsonUtil.isJsonData(strObject)) {
                    try {
                        JSONArray array = new JSONArray(strObject);
                        if (array.length() > 0) {
                            for (int i = 0; i < array.length(); i++) {
                                JSONObject object = array.optJSONObject(i);
                                if (object.getInt(GTSConst.JSON_KEY_TRADESTATE) != AppContances.TRADE_STATU_ENABLE) {
                                    DataManager.instance().setLoadDataState(iNotification + "", true);
                                    break;
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                if (iNotification == GTSConst.ZONE_TYPE_SELF) {
                    if (JsonUtil.isJsonData(strObject)) {
                        DataManager.instance().setLoadDataState(iNotification + "", true);
                        DataManager.instance().addSelfTickList(strObject);
                        DataManager.instance().validateSelfTick();
                    } else {
                        DataManager.instance().mSelfCode.clear();
                    }
                    if (DataManager.instance().getLoadDataState(GTSConst.ZONE_TYPE_ALL + "")) {
                        RxBus.getInstance().postSticky(GTSConst.REPLY_SYMBOL_LIST + "", bundleRxBus(iNotification, iValue, strObject));
                    }
                }
            }
            break;
            case GTSConst.REPLY_SYMBOL_TICK_UPDATE: {
//                Logger.i("onServerResponse 每口报价回包接收到回调 " + iNotification + " iValue = " + iValue + " strObject = " + strObject);
                DataItemDetail tickModel = null;
                if (JsonUtil.isJsonData(strObject)) {
                    try {
                        JSONArray mArray = new JSONArray(strObject);
                        if (mArray.length() > 0) {
                            JSONObject model = mArray.getJSONObject(0);
                            DataItemDetail tmp = DataManager.instance().updateTickList(model.optInt(GTSConst.JSON_KEY_CODEID), model);
                            if (null != tmp) {
                                tickModel = tmp.Copy();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                RxBus.getInstance().post(GTSConst.REPLY_SYMBOL_TICK_UPDATE + "", tickModel);
            }
            break;
            case GTSConst.REPLY_SYMBOL_UPDATE:
                Logger.i("onServerResponse 行情列表产品更新接收到回调REPLY_SYMBOL_UPDATE iNotification = " + iNotification + " iValue = " + iValue + " strObject = ");
                DataItemDetail tickModel = null;
                if (JsonUtil.isJsonData(strObject)) {
                    try {
                        JSONArray mArray = new JSONArray(strObject);
                        if (mArray.length() > 0) {
                            JSONObject model = mArray.getJSONObject(0);
                            tickModel = DataManager.instance().updateSymbolList(model.optInt(GTSConst.JSON_KEY_CODEID), model);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    RxBus.getInstance().post(GTSConst.REPLY_SYMBOL_UPDATE + "", tickModel);
                }
                break;
            case GTSConst.REPLY_POSTION_LIST: {
                Logger.i("onServerResponse 持仓列表回包接收到回调REPLY_POSTION_LIST iNotification = " + iNotification + " iValue = " + iValue + " strObject = ");
                if (JsonUtil.isJsonData(strObject)) {
                    DataManager.instance().addPositionList(strObject);
                } else {
                    DataManager.instance().mPositionInfoList.clear();
                }
                DataManager.instance().setLoadDataState(ConfigType.TAB_POSITION_TYPE, true);
                RxBus.getInstance().postSticky(GTSConst.REPLY_POSTION_LIST + "", bundleRxBus(iNotification, iValue, strObject));
            }
            break;
            case GTSConst.REPLY_POSTION_UPDATELIST: {
//                Logger.i("onServerResponse 持仓列表更新 iNotification = " + iNotification + " iValue = " + iValue);
                ArrayList<Integer> object = null;
                if (JsonUtil.isJsonData(strObject)) {
                    object = DataManager.instance().updatePositionList(iNotification, strObject);
                }
                Bundle bundle = new Bundle();
                bundle.putInt("iNotification", iNotification);
                bundle.putInt("iValue", iValue);
                bundle.putIntegerArrayList("object", object);
                RxBus.getInstance().post(GTSConst.REPLY_POSTION_UPDATELIST + "", bundle);
            }
            break;
            case GTSConst.REPLY_POSTION_UPDATE: {
                Logger.i("onServerResponse 持仓列表单条订单更新REPLY_POSTION_UPDATE iNotification = " + iNotification + " iValue = " + iValue + " strObject = " + strObject);
                if (JsonUtil.isJsonData(strObject)) {
                    DataManager.instance().updateOnePosition(strObject);
                }
                RxBus.getInstance().post(GTSConst.REPLY_POSTION_UPDATE + "", bundleRxBus(iNotification, iValue, strObject));
            }
            break;
            case GTSConst.REPLY_POSTION_ADD: {
                cmd = GTSConst.REPLY_POSTION_LIST;
                Logger.i("onServerResponse 持仓列表添加REPLY_POSTION_ADD iNotification = " + iNotification + " iValue = " + iValue + " strObject = " + strObject);
                if (JsonUtil.isJsonData(strObject)) {
                    DataManager.instance().addOnePositionList(strObject);
                }
                RxBus.getInstance().postSticky(GTSConst.REPLY_POSTION_LIST + "", bundleRxBus(iNotification, iValue, strObject));
            }
            break;
            case GTSConst.REPLY_POSTION_DELETE: {
                cmd = GTSConst.REPLY_POSTION_LIST;
                Logger.i("onServerResponse 持仓列表删除REPLY_POSTION_DELETE iNotification = " + iNotification + " iValue = " + iValue + " strObject = ");
                DataManager.instance().removePosition(iNotification);
                RxBus.getInstance().postSticky(GTSConst.REPLY_POSTION_LIST + "", bundleRxBus(iNotification, iValue, strObject));
            }
            break;
            case GTSConst.REPLY_DEAL_LIST: {
                Logger.i("onServerResponse 当日成交列表回包接收到回调REPLY_DEAL_LIST iNotification = " + iNotification + " iValue = " + iValue + " strObject = ");
                if (JsonUtil.isJsonData(strObject)) {
                    DataManager.instance().addDealList(strObject);
                } else {
                    DataManager.instance().mDealInfoList.clear();
                }
                DataManager.instance().setLoadDataState(ConfigType.TAB_DEAL_TYPE, true);
                RxBus.getInstance().postSticky(GTSConst.REPLY_DEAL_LIST + "", bundleRxBus(iNotification, iValue, strObject));
            }
            break;
            case GTSConst.REPLY_DEAL_ADD: {
                cmd = GTSConst.REPLY_DEAL_LIST;
                Logger.i("onServerResponse 当日成交列表添加REPLY_DEAL_ADD iNotification = " + iNotification + " iValue = " + iValue + " strObject = ");
                if (JsonUtil.isJsonData(strObject)) {
                    try {
                        JSONObject mArray = new JSONObject(strObject);
                        final DataItemDetail mDealData = new DataItemDetail();
                        JsonUtil.toDataItemDetail(mDealData, mArray);
                        DataManager.instance().addOneDealList(mDealData);

                        //成交提示弹层
                        if (null != mDealData) {
                            Logger.i("onServerResponse 当日成交列表添加 mDealData2.dealType = " + mDealData.getInt(GTSConst.JSON_KEY_DEALTYPE));
                            if (mDealData.getInt(GTSConst.JSON_KEY_DEALTYPE) == AppContances.ORDER_TYPE_APPLY_TYPE
                                    || mDealData.getInt(GTSConst.JSON_KEY_DEALTYPE) == AppContances.ORDER_TYPE_APPLY_STOP_TYPE
                                    || mDealData.getInt(GTSConst.JSON_KEY_DEALTYPE) == AppContances.ORDER_TYPE_STOP_TYPE
                                    || mDealData.getInt(GTSConst.JSON_KEY_DEALTYPE) == AppContances.ORDER_TYPE_LIMIT_TYPE
                                    || mDealData.getInt(GTSConst.JSON_KEY_DEALTYPE) == AppContances.ORDER_TYPE_FORCE_CLOSE_TYPE
                                    || mDealData.getInt(GTSConst.JSON_KEY_DEALTYPE) == AppContances.SYS_ORDER_TYPE_FORCE_CLOSE_TYPE) {
                                final BaseActivity mOwnerAct = (BaseActivity) AppActivities.getSingleton().currentActivity();
                                if (null != mOwnerAct && !mOwnerAct.isFinishing()) {
                                    mOwnerAct.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            mOwnerAct.showOrderTips(mOwnerAct, mDealData);
                                        }
                                    });
                                }
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                //发送通知
                RxBus.getInstance().postSticky(GTSConst.REPLY_DEAL_LIST + "", bundleRxBus(iNotification, iValue, strObject));
            }
            break;
            case GTSConst.REPLY_WIN_LIST: {
                Logger.i("onServerResponse 当日盈亏列表回包接收到回调REPLY_WIN_LIST iNotification = " + iNotification + " iValue = " + iValue + " strObject = ");
                if (JsonUtil.isJsonData(strObject)) {
                    DataManager.instance().addCloseList(strObject);
                } else {
                    DataManager.instance().mCloseList.clear();
                }
                DataManager.instance().setLoadDataState(ConfigType.TAB_PROFIT_TYPE, true);
                RxBus.getInstance().postSticky(GTSConst.REPLY_WIN_LIST + "", bundleRxBus(iNotification, iValue, strObject));
            }
            break;
            case GTSConst.REPLY_WIN_ADD: {
                cmd = GTSConst.REPLY_WIN_LIST;
                Logger.i("onServerResponse 当日盈亏列表添加REPLY_WIN_ADD iNotification = " + iNotification + " iValue = " + iValue + " strObject = ");
                if (JsonUtil.isJsonData(strObject)) {
                    DataManager.instance().addOneCloseList(strObject);
                }
                //发送通知
                RxBus.getInstance().postSticky(GTSConst.REPLY_WIN_LIST + "", bundleRxBus(iNotification, iValue, strObject));
            }
            break;
            case GTSConst.REPLY_ORDER_LIST: {
                Logger.i("onServerResponse 挂单列表回包接收到回调REPLY_ORDER_LIST iNotification = " + iNotification + " iValue = " + iValue + " strObject = ");
                if (JsonUtil.isJsonData(strObject)) {
                    DataManager.instance().addOrderList(strObject);
                } else {
                    DataManager.instance().mOrderInfoList.clear();
                }
                DataManager.instance().setLoadDataState(ConfigType.TAB_PENDING_TYPE, true);
                RxBus.getInstance().postSticky(GTSConst.REPLY_ORDER_LIST + "", bundleRxBus(iNotification, iValue, strObject));
            }
            break;
            case GTSConst.REPLY_ORDER_UPDATELIST: {
                //Logger.i("onServerResponse 挂单列表更新 iNotification = " + iNotification + " iValue = " + iValue + " strObject = " + strObject);
                if (JsonUtil.isJsonData(strObject)) {
                    DataManager.instance().updateOrderList(strObject);
                }
                RxBus.getInstance().postSticky(GTSConst.REPLY_ORDER_UPDATELIST + "", bundleRxBus(iNotification, iValue, strObject));
            }
            break;
            case GTSConst.REPLY_ORDER_UPDATE: {
                cmd = GTSConst.REPLY_ORDER_LIST;
                Logger.i("onServerResponse 挂单列表单条订单更新 iNotification = " + iNotification + " iValue = " + iValue + " strObject = " + strObject);
                if (JsonUtil.isJsonData(strObject)) {
                    DataManager.instance().updateOneOrderList(strObject);
                }
                RxBus.getInstance().postSticky(GTSConst.REPLY_ORDER_LIST + "", bundleRxBus(iNotification, iValue, strObject));
            }
            break;
            case GTSConst.REPLY_ORDER_ADD: {
                cmd = GTSConst.REPLY_ORDER_LIST;
                Logger.i("onServerResponse 挂单列表添加REPLY_ORDER_ADD iNotification = " + iNotification + " iValue = " + iValue + " strObject = " + strObject);
                if (JsonUtil.isJsonData(strObject)) {
                    DataManager.instance().addOneOrderList(strObject);
                }
                RxBus.getInstance().postSticky(GTSConst.REPLY_ORDER_LIST + "", bundleRxBus(iNotification, iValue, strObject));
            }
            break;
            case GTSConst.REPLY_ORDER_CANCEL:
            case GTSConst.REPLY_ORDER_DELETE: {
                cmd = GTSConst.REPLY_ORDER_LIST;
                Logger.i("onServerResponse 挂单列表删除 iNotification = " + iNotification + " iValue = " + iValue + " strObject = ");
                DataManager.instance().removeOrder(iNotification);
                RxBus.getInstance().postSticky(GTSConst.REPLY_ORDER_LIST + "", bundleRxBus(iNotification, iValue, strObject));
            }
            break;
            case GTSConst.REPLY_ORDER_SUCCESS: {
                Logger.i("onServerResponse 下单成功通知REPLY_ORDER_SUCCESS cmd = " + cmd + " iNotification = " + iNotification
                        + " iValue = " + iValue + "seqList ==  " + seqList.get(iNotification + "") + "str = " + strObject);
                if (seqList.get(iNotification + "").equals(AppContances.ORDER_TYPE_ORDER_CANCEL + "")) {
                    //撤单
                    RxBus.getInstance().post(GTSConst.REPLY_ORDER_CANCEL + "", bundleRxBus(iNotification, 0, strObject));
                } else {
                    DataItemDetail itemDetail = null;
                    if (JsonUtil.isJsonData(strObject)) {
                        try {
                            JSONObject object = new JSONObject(strObject);
                            itemDetail = new DataItemDetail();
                            JsonUtil.toDataItemDetail(itemDetail, object);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    if (null == itemDetail || !itemDetail.isValidDetailData()) {
                        if (seqList.get(iNotification + "").equals(AppContances.ORDER_TYPE_MARKET + "")) {
                            //市价
                            itemDetail = DataManager.instance().getPositionModel(iValue);
                        } else if (seqList.get(iNotification + "").equals(AppContances.ORDER_TYPE_APPLY + "")) {
                            //挂单
                            itemDetail = DataManager.instance().getOrderModel(iValue);
                        } else if (seqList.get(iNotification + "").equals(AppContances.ORDER_TYPE_CLOSE + "")) {
                            //平仓
                            itemDetail = DataManager.instance().getCloseModel(iValue);
                            if (itemDetail.getString(GTSConst.JSON_KEY_DIRECTION).equals(String.valueOf(AppContances.TRADE_TYPE_BUY))) {
                                PackStatis.getToService(PackStatis.EventAction.SELL.getValue(), PackStatis.EventCategory.TRADE.getValue(), null, "1");
                            } else if (itemDetail.getString(GTSConst.JSON_KEY_DIRECTION).equals(String.valueOf(AppContances.TRADE_TYPE_SALE))) {
                                PackStatis.getToService(PackStatis.EventAction.SELL.getValue(), PackStatis.EventCategory.TRADE.getValue(), null, "0");
                            }
                        } else if (seqList.get(iNotification + "").equals(AppContances.ORDER_TYPE_MODIFY + "")) {
                            //设置止损止盈
                            itemDetail = DataManager.instance().getPositionModel(iValue);
                        } else if (seqList.get(iNotification + "").equals(AppContances.ORDER_TYPE_APPLY_MODIFY + "")) {
                            //改单
                            itemDetail = DataManager.instance().getOrderModel(iValue);
                        } else {
                            Logger.e("下单成功通知 seq 不匹配类型 " + seqList.get(iNotification + ""));
                        }
                    }
                    DataItemDetail successItem = new DataItemDetail();
                    if (null != itemDetail) {
                        successItem = itemDetail.Copy();
                    } else {
                        Logger.e("下单成功通知 itemDetail is null");
                    }
                    successItem.Dump();
                    removeSeqList(iNotification + "");

                    Bundle bundle = new Bundle();
                    bundle.putInt("iNotification", iNotification);
                    bundle.putInt("iValue", iValue);
                    bundle.putParcelable("model", successItem);

                    RxBus.getInstance().post(GTSConst.REPLY_ORDER_SUCCESS + "", bundle);
                }
            }
            break;

            case GTSConst.REPLY_ORDER_FAILED: {
                Logger.i("onServerResponse 下单失败通知REPLY_ORDER_FAILED cmd = " + cmd + " iNotification = " + iNotification
                        + " iValue = " + iValue);
                if (seqList.containsKey(iNotification + "")) {
                    if (seqList.get(iNotification + "").equals(AppContances.ORDER_TYPE_ORDER_CANCEL + "")) {
                        RxBus.getInstance().post(GTSConst.REPLY_ORDER_CANCEL + "", bundleRxBus(iNotification, iValue, strObject));
                    } else {
                        RxBus.getInstance().post(GTSConst.REPLY_ORDER_FAILED + "", bundleRxBus(iNotification, iValue, strObject));
                    }
                } else {
                    //系统成交的错误通知
                    if (iValue == 39) {
                        final BaseActivity mOwnerAct = (BaseActivity) AppActivities.getSingleton().currentActivity();
                        final int errorId = iValue;
                        if (null != mOwnerAct && !mOwnerAct.isFinishing() && mOwnerAct.isResumed) {

                            mOwnerAct.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mOwnerAct.showToastPopWindow(ConfigUtil.instance().getErrorConfigObject().optString(errorId + ""));
                                }
                            });
                        }
                    }
                }
            }
            break;

            case GTSConst.REPLY_MSG_GETINDICATOR: {
                //获取指标参数
                GTTFormularContent mSuperFormularContent = new GTTFormularContent();
                GTTFormularContent mSecondFormularContent = new GTTFormularContent();
                AppTerminal.instance().getFormularContent(ChartConfig.instance().getMainKType(), mSuperFormularContent, 0);
                mSuperFormularContent.setParamNum();
                AppTerminal.instance().getFormularContent(ChartConfig.instance().getSecondKType(), mSecondFormularContent, 0);

                final GTTIndexDataRequest mGttIndexDataRequest = ReqDataUtils.instance().reqIndictorData(iNotification, -GTTKDataManager.instance().kLineNumbers, 0, 0);
                //指标切换时处理
                Logger.i("onServerResponse 指标切换数据回包REPLY_MSG_GETINDICATOR cmd = " + cmd + " iNotification = " + iNotification);
                Bundle bundle = new Bundle();
                bundle.putInt("iNotification", iNotification);
                bundle.putInt("iValue", iValue);
                bundle.putString("strObject", strObject);
                bundle.putSerializable("SuperFormularContent", mSuperFormularContent);
                bundle.putSerializable("SecondFormularContent", mSecondFormularContent);
                bundle.putSerializable("mGttIndexDataRequest", mGttIndexDataRequest);

                RxBus.getInstance().post(GTSConst.REPLY_MSG_GETINDICATOR + "", bundle);
            }
            break;

            case GTSConst.REPLY_UPTRENDTICK_UPDATE: {
                //分时最后一根线数据处理
                GTTTimeDataModel mRound = new GTTTimeDataModel();
                AppTerminal.instance().getUptrendDataLatest(iNotification, mRound);
                Logger.i("onServerResponse 分时最后一根线数据回包 cmd = " + cmd + " iNotification = " + iNotification + " iValue = " + iValue + mRound.toString());
                Bundle bundle = new Bundle();
                bundle.putInt("iNotification", iNotification);
                bundle.putInt("iValue", iValue);
                bundle.putSerializable("object", mRound);

                RxBus.getInstance().post(GTSConst.REPLY_UPTRENDTICK_UPDATE + "", bundle);
            }
            break;
            case GTSConst.REPLY_KLINETICK_UPDATE: {
                //k线最后一根线数据处理
                GTTKDataModel mKline = new GTTKDataModel();
                AppTerminal.instance().getKLineDataLatest(iNotification, ChartConfig.instance().getChartPeriodicity().nativeKLineType(), 0, mKline);
                Logger.i("onServerResponse k线最后一根线数据回包 cmd = " + cmd + " iNotification = " + iNotification + " iValue = " + iValue + mKline.toString());

                //int addLineNumber = ReqDataUtils.instance().updataOrAddLastLine(iNotification,ChartConfig.instance().getChartPeriodicity().nativeKLineType(),mKline);
                GTTIndexDataRequest gttIndexDataRequest = ReqDataUtils.instance().reqIndictorData(iNotification, -GTTKDataManager.instance().getSize(), 0, 0);
                Bundle bundle = new Bundle();
                bundle.putInt("iNotification", iNotification);
                bundle.putInt("iValue", iValue);
                bundle.putSerializable("object", mKline);
                bundle.putSerializable("mRequest", gttIndexDataRequest);

                RxBus.getInstance().post(GTSConst.REPLY_KLINETICK_UPDATE + "", bundle);
            }
            break;

            case GTSConst.REPLY_UPTRENDDATA_NEXTDAY: {
                //分时图数据最后一根线更新到达第二个交易日
                Logger.i("onServerResponse 分时图数据最后一根线更新到达第二个交易日REPLY_UPTRENDDATA_NEXTDAY cmd = " + cmd + " iNotification = " + iNotification);
                RxBus.getInstance().post(GTSConst.REPLY_UPTRENDDATA_NEXTDAY + "", bundleRxBus(iNotification, iValue, strObject));
            }
            break;

            case GTSConst.REPLY_HTTP_RGS: {
                Logger.i("onServerResponse 单点登录回包通知REPLY_HTTP_RGS cmd = " + cmd + " iNotification = " + iNotification
                        + " iValue = " + iValue + " strObject = " + strObject);
                RxBus.getInstance().post(GTSConst.REPLY_HTTP_RGS + "", bundleRxBus(iNotification, iValue, strObject));
            }
            break;

            case GTSConst.REPLY_HTTP_UPDATE: {
                Logger.i("onServerResponse 版本更新回包通知REPLY_HTTP_UPDATE cmd = " + cmd + " iNotification = " + iNotification
                        + " iValue = " + iValue + " strObject = " + strObject);
                RxBus.getInstance().post(GTSConst.REPLY_HTTP_UPDATE + "", bundleRxBus(iNotification, iValue, strObject));
            }
            break;
            case GTSConst.REPLY_HTTP_UPDATE_PASS: {
                Logger.i("onServerResponse 修改密码回包通知REPLY_HTTP_UPDATE_PASS cmd = " + cmd + " iNotification = " + iNotification
                        + " iValue = " + iValue + " strObject = " + strObject);
                RxBus.getInstance().post(GTSConst.REPLY_HTTP_UPDATE_PASS + "", bundleRxBus(iNotification, iValue, strObject));
            }
            break;
            case GTSConst.REPLY_HTTP_NOTIFY_LIST: {
                Logger.i("onServerResponse (分类)消息中心回包通知REPLY_HTTP_NOTIFY_LIST cmd = " + cmd + " iNotification = " + iNotification
                        + " iValue = " + iValue + " strObject = " + strObject);
                RxBus.getInstance().post(GTSConst.REPLY_HTTP_NOTIFY_LIST + "", bundleRxBus(iNotification, iValue, strObject));
            }
            break;
            case GTSConst.REPLY_HTTP_NOTIFY_DETAIL: {
                Logger.i("onServerResponse 消息详情回包通知REPLY_HTTP_NOTIFY_DETAIL cmd = " + cmd + " iNotification = " + iNotification
                        + " iValue = " + iValue + " strObject = " + strObject);
                RxBus.getInstance().post(GTSConst.REPLY_HTTP_NOTIFY_DETAIL + "", bundleRxBus(iNotification, iValue, strObject));
            }
            break;
            case GTSConst.REPLY_HTTP_NEWS_LIST: {
                Logger.i("onServerResponse 资讯列表回包通知REPLY_HTTP_NEWS_LIST cmd = " + cmd + " iNotification = " + iNotification
                        + " iValue = " + iValue + " strObject = " + strObject);
                RxBus.getInstance().post(GTSConst.REPLY_HTTP_NEWS_LIST + "", bundleRxBus(iNotification, iValue, strObject));
            }
            break;
            case GTSConst.REPLY_MOBILE_INFO: {
                Logger.i("onServerResponse 获取手机号码回包通知REPLY_MOBILE_INFO cmd = " + cmd + " iNotification = " + iNotification
                        + " iValue = " + iValue + " strObject = " + strObject);
                if (!"".equals(strObject)) {
                    GTConfig.instance().mCurLoginPhone = strObject;
                }
                RxBus.getInstance().post(GTSConst.REPLY_MOBILE_INFO + "", bundleRxBus(iNotification, iValue, strObject));
            }
            break;
            case GTSConst.REPLY_HTTP_NORMALREQ: {
                String seqValue = seqList.get(iNotification + "");
                Logger.i("onServerResponse 配置中心通用接口回包通知REPLY_HTTP_NORMALREQ cmd = " + cmd + " iNotification = " + iNotification
                        + " iValue = " + iValue + " strObject = " + strObject + ", " + seqList.get(iNotification + ""));
                if (seqList.get(iNotification + "").equals(AppContances.NORMALREQ_TYPE_GET_TOKEN)) {
                    RxBus.getInstance().post(GTSConst.REPLY_TYPE_GET_TOKEN, bundleRxBus(iNotification, iValue, strObject));
                } else if (seqList.get(iNotification + "").equals(AppContances.NORMALREQ_TYPE_GET_RELATEDCUSTOMER)) {
                    RxBus.getInstance().post(GTSConst.REPLY_TYPE_GET_CUSTOMER, bundleRxBus(iNotification, iValue, strObject));
                } else if (seqList.get(iNotification + "").equals(AppContances.NORMALREQ_TYPE_GET_CUSTOMERBYMOBILE)) {
                    RxBus.getInstance().post(GTSConst.REPLY_TYPE_BINDCUSTOMER, bundleRxBus(iNotification, iValue, strObject));
                } else if (seqList.get(iNotification + "").equals(AppContances.NORMALREQ_TYPE_BINDCUSTOMER)) {
                    RxBus.getInstance().post(GTSConst.REPLY_TYPE_BINDCUSTOMER, bundleRxBus(iNotification, iValue, strObject));
                } else if (seqList.get(iNotification + "").equals(AppContances.NORMALREQ_TYPE_GET_BANK_INFO)) {
                    RxBus.getInstance().post(GTSConst.NORMALREQ_TYPE_GET_BANK_INFO, bundleRxBus(iNotification, iValue, strObject));
                } else if (seqList.get(iNotification + "").equals(AppContances.NORMALREQ_TYPE_GET_BANK_CARD_INFO)) {
                    RxBus.getInstance().post(GTSConst.NORMALREQ_TYPE_GET_BANK_CARD_INFO, bundleRxBus(iNotification, iValue, strObject));
                }
            }
            break;
        }
    }

    /**
     * 发送通知
     *
     * @param iNotification
     * @param iValue
     * @param object
     */
    private synchronized Bundle bundleRxBus(int iNotification, int iValue, String object) {
        Bundle bundle = new Bundle();
        bundle.putInt("iNotification", iNotification);
        bundle.putInt("iValue", iValue);
        bundle.putString("strObject", object);
        return bundle;
    }
}
